package com.xz.group12306.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.Position;
import com.alibaba.fastjson.JSON;
import com.xz.group12306.utils.CommonConstants;
import com.xz.group12306.utils.FileUtil;
import com.xz.group12306.utils.UploadIconResponse;




/**
 * Servlet implementation class UserIconSaverServlet
 */
public class UserIconSaverServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final String RESPONSE_START = "<!DOCTYPE html><html><head><title></title></head><body><script type='text/javascript'>";
	
	private static final String RESPONSE_ENDED = "</script></body></html>";

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 通过线程找到类加载路径，进而找到 classes 目录的实际路径
		String classPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
		
		// 利用相对路径算出 存储头像的路径
		classPath += "../../" + CommonConstants.ICON_FOLDER;
		
		// 获取当前的时间戳
		long time = (new Date()).getTime();
		
		// 结合以上数据为基础计算出一个新的文件路径用于存储图片本身
		File target = new File(classPath + File.separator + time + ".jpg");
		
		// 将路径归一
		target = target.getCanonicalFile();
        
        // 确保目标文件所在目录都存在
        target.getParentFile().mkdirs();
        
        // 从请求获取数据流
        ServletInputStream in = request.getInputStream();
        
        // 新建图片的存储输出流
        FileOutputStream fileOutputStream =new FileOutputStream(target);
        
        // 从请求对象读取出报文字节数组
        byte[] dataBody = FileUtil.readBody(request);
        // 以 ISO-8859-1 编码方式转换成字符串
        String textBody = new String(dataBody, "ISO-8859-1");
        // 计算出图片数据在字节数组中的偏移量
        Position p = (Position) FileUtil.getFilePosition(request, textBody);
        // 结合输出流，报文字节数组，读取偏移量 将图片保存至硬盘
        FileUtil.writeTo(fileOutputStream, dataBody, (com.xz.group12306.utils.FileUtil.Position) p);


        // 新建一个文件上传响应消息对象，其中包含图片在网站中的相对路径
        UploadIconResponse uiresponse = new UploadIconResponse();
        uiresponse.setUrl(CommonConstants.ICON_FOLDER + time + ".jpg");
        
        // 设定响应消息的 MIME 为 纯文本，要求浏览器不出处理，然后输出 JSON 字符串
        response.setContentType("text/html");
        response.getWriter().append(RESPONSE_START).append("var response = ").append(JSON.toJSONString(uiresponse)).append(RESPONSE_ENDED);
	    
	}
}
